﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Input;
using System.Windows.Controls;
using System.Diagnostics;
using System.Windows.Interop;
using System.Windows.Media.Imaging;
using io = System.IO;
using System.Threading;
using System.Windows.Threading;
using wf = System.Windows.Forms;
using dw = System.Drawing;
using System.Windows.Shapes;
using xnaGraphics = Microsoft.Xna.Framework.Graphics;
using xna = Microsoft.Xna.Framework;

namespace client.app.gui2
{
    public class MainWindow : Window
    {
        public comm.TimeStat UpdateTimeStat { get; private set; }
        public comm.TimeStat DrawTimeStat { get; private set; }

        public const int FLAG_WIDTH = 36;
        public const int FLAG_HEIGHT = 20;
        public const string FLAG_CACHE_PREFIX = "FACTION_FLAG_";

        Application _app = null;
        MainUI _mainUI = null;

        Grid _gridRoot = null;
        Grid _gridCacheCanvas = null;
        xnaGraphics.SpriteBatch _spriteBatch = null;
        List<CacheDrawCanvas> _cacheCanvasList = new List<CacheDrawCanvas>();
        CacheDrawCanvas _cacheTexCanvas = null;

        public MainWindow(Application app)
        {
            _app = app;
            Background = null;
            FontSize = 13;
            FontFamily = new FontFamily("微软雅黑");
            AllowsTransparency = true;
            WindowStyle = WindowStyle.None;
            ShowInTaskbar = false;
            UseLayoutRounding = true;
            SnapsToDevicePixels = true;

            Width = 1024;
            Height = 1024;

            Top = 0;
            Left = 0;

            Top = -Width;
            Left = -Height;

            UpdateTimeStat = new comm.TimeStat();
            DrawTimeStat = new comm.TimeStat();

            _gridRoot = new Grid();
            _gridRoot.Background = new SolidColorBrush(Color2.Black());

            _gridCacheCanvas = new Grid();
            _gridRoot.Children.Add(_gridCacheCanvas);

            Content = _gridRoot;

            KeyDown += new KeyEventHandler(MainWindow_KeyDown);
        }

        void MainWindow_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                Close();
            }
        }

        public void ShowLoading(string txt)
        {
            Dispatcher.BeginInvoke(new Action(() =>
            {
                _mainUI.ShowLoading(txt);
            }));
        }
        public void HideLoading()
        {
            Dispatcher.BeginInvoke(new Action(() =>
            {
                _mainUI.HideLoading();
            }));
        }
        public void ShowMain()
        {
            Dispatcher.BeginInvoke(new Action(() =>
            {
                _mainUI.ShowMain();
            }));
        }
        public void ShowHeroList()
        {
            Dispatcher.BeginInvoke(new Action(() =>
            {
                _mainUI.ShowHeroList();
            }));
        }
        public void Exit()
        {
            Dispatcher.Invoke(new Action(() =>
            {
                _app.Shutdown();
            }));
        }

        public xna.Vector2 GetOffset(FrameworkElement element)
        {
            var pt = element.TranslatePoint(new Point(), this);
            return new xna.Vector2((int)pt.X, (int)pt.Y);
        }

        public CacheDrawCanvas CreateCacheCanvas()
        {
            var cv = new CacheDrawCanvas();
            _cacheCanvasList.Add(cv);
            _gridCacheCanvas.Children.Add(cv.Element);
            return cv;
        }

        public void DrawCacheTex(xnaGraphics.SpriteBatch spriteBatch, string key, xna.Vector2? point = null)
        {
            _cacheTexCanvas.Draw(spriteBatch, key, point);
        }
        public void UpdateCahceTex()
        {
            Dispatcher.BeginInvoke(new Action(() =>
            {
                _cacheTexCanvas.ClearElement();
                var allFac = MainGame.MainSpace.GetAllFactionInfo();
                foreach (var facInfo in allFac)
                {
                    var color = Color.FromRgb(facInfo.Color.R, facInfo.Color.G, facInfo.Color.B);
                    var bitmap = new BitmapImage();
                    bitmap.FromBytes(facInfo.FlagImageBytes);
                    _cacheTexCanvas.AddElement(FLAG_CACHE_PREFIX + facInfo.FactionId, new Border
                    {
                        Width = FLAG_WIDTH,
                        Height = FLAG_HEIGHT,
                        Margin = new Thickness(0, 0, 4, 4),
                        BorderBrush = new SolidColorBrush(Color2.White(80)),
                        Background = new SolidColorBrush(Color2.FromColor(255 / 100 * 50, color)),
                        BorderThickness = new Thickness(1),
                        Child = new Image
                        {
                            Source = bitmap,
                            Width = bitmap.PixelWidth,
                            Height = bitmap.PixelHeight
                        }
                    });
                }
            }));
        }
        public void MainGameLoadContent()
        {
            _spriteBatch = new xnaGraphics.SpriteBatch(MainGame.Instance.GraphicsDevice);

            Dispatcher.Invoke(new Action(() =>
            {
                _cacheTexCanvas = CreateCacheCanvas();

                _mainUI = new MainUI
                {
                    HorizontalAlignment = HorizontalAlignment.Left,
                    VerticalAlignment = VerticalAlignment.Top
                };
                _gridRoot.Children.Add(_mainUI);

                #region Rendering
                CompositionTarget.Rendering += new EventHandler((o, e) =>
                {
                    Update();
                });
                #endregion
            }));

            TcpClient.Connect(succ =>
            {
                Console.WriteLine("Connect Server:" + succ);
                if (succ)
                {
                    ShowHeroList();
                }
            });
        }
        public bool CallMouseEvent(MouseEventType type, int x, int y)
        {
            Dispatcher.Invoke(new Action(() =>
            {
                _mainUI.CallMouseEvent(type, new Point(x, y));
            }));
            return _mainUI.StopEvent;
        }

        public void Update()
        {
            UpdateTimeStat.Update();

            //System.Console.WriteLine("----------------");

            if (_mainUI != null)
            {
                _mainUI.Update(UpdateTimeStat);
            }

            var cvs = _cacheCanvasList.ToArray();
            foreach (var cv in cvs)
            {
                cv.Update(UpdateTimeStat);
            }
        }
        public void Draw()
        {
            DrawTimeStat.Update();

            if (_mainUI != null)
            {
                _spriteBatch.Begin();
                _mainUI.Draw(DrawTimeStat, _spriteBatch);
                _spriteBatch.End();
            }
        }
    }
}
